package com.youbug.kefu.service.impl;

import com.youbug.kefu.entity.Org;
import com.youbug.kefu.service.ICommonService;
import com.youbug.kefu.service.IOrgService;
import com.youbug.kefu.vo.CommonTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommonService implements ICommonService {

    @Autowired
    private IOrgService orgService;

    @Override
    public List<CommonTreeVo> getOrgTree() {
        List<Org> orgs = orgService.getOrgs();

        return  getChildren(orgs);
    }

    private List<CommonTreeVo> getChildren(List<Org> orgs) {
        List<CommonTreeVo> treeVos = new ArrayList<>(orgs.size());
        for (Org org : orgs){
            List<Org> subOrgs = org.getChildren();
            CommonTreeVo treeVo = new CommonTreeVo();
            treeVo.setLabel(org.getName());
            treeVo.setValue(String.valueOf(org.getId()));
            treeVo.setChildren(getChildren(subOrgs));
            treeVos.add(treeVo);
        }

        return treeVos;
    }
}
